package reentrantlock;

/**
 * https://juejin.cn/post/6844904066317828104
 */
public class MyLockDemo {

    private static MyLock lock = new MyReentrantLock();

    public static void main(String[] args) {
//        differentThread();
        sameThread();
    }

    private static void differentThread() {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("t1已经启动"); //step1
                    lock.lock();
                    System.out.println("t1获取到锁"); //step2
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                    System.out.println("t1释放锁");
                }
            }
        }, "t1");
        t1.start();

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("t2已经启动"); //step3
                    lock.lock();
                    System.out.println("t2获取到锁"); //BLOCKED
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                    System.out.println("t1释放锁"); //BLOCKED
                }
            }
        }, "t2");
        t2.start();
    }

    private static void sameThread() {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("t已经启动");
                    lock.lock();
                    System.out.println("t第一次获取到锁");
                    lock.lock();
                    System.out.println("t第二次获取到锁");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                    lock.unlock();
                }
            }
        }, "t");
        t.start();
    }
}
